package Game.window;

import java.awt.Canvas;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;

import Game.Constantes;
import Game.scene.IScene;
import Game.scene.Stage;
import Game.scene.StartScreen;

public class GameMain implements Runnable{

	public static GameMain instance;

	public static int PWIDTH;
	public static int PHEIGHT;

	int FPS,SFPS;
	long SegundoAtual = 0;
	long NovoSegundo = 0;

	IScene TelaAtiva = null;

	public Canvas display_parent;

	public Thread animator;
	public boolean running = false;

	public GameMain() {
		
		instance = this;
		display_parent = new Canvas();
		display_parent.setSize(Constantes.WindowWidth,Constantes.WindowHeight);
		display_parent.setFocusable(true);
		display_parent.requestFocus();
		display_parent.setIgnoreRepaint(true);
	}

	public void start(){
		if (animator == null || !running) {
			animator = new Thread(this);

			animator.setPriority(Thread.MAX_PRIORITY);

			animator.start();
		}
	}

	public void init ()
	{
		Stage tela = new Stage();
		tela.init();
		TelaAtiva = tela;
	}   
	
//	public void changeScreen(String screen){
//		if(screen.equals("game")){
//			StartScreen tela = new StartScreen();
//			tela.init();
//			TelaAtiva = tela;
//			running = false;
//			start();
//		}
//	}

	long segundoatual = 0;
	long diftime = 0;
	int ultimosegundo = 0;
	int somaframes = 0;

	@Override
	public void run() {
		running = true;

		try {
			Display.setParent(display_parent);
			Display.create();
		} catch (LWJGLException e) {
			e.printStackTrace();
		}

		init();

		while(running) {
			if(TelaAtiva!=null){
				TelaAtiva.update(diftime);
				TelaAtiva.render();
				Display.update();
			}

			if(segundoatual>0){
				diftime = System.currentTimeMillis() - segundoatual;
			}
			segundoatual = System.currentTimeMillis();

			if(((int)(segundoatual/1000))!=ultimosegundo){
//				System.out.println(" _FPS "+somaframes);
				somaframes = 0;
			}
			somaframes++;
			ultimosegundo = (int)(segundoatual/1000);
		}

		Display.destroy();
	}    
}

